
package com.xiaoma.myaudience.biz.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.xiaoma.myaudience.R;
import com.xiaoma.myaudience.biz.adapter.ReviewListAdapter;
import com.xiaoma.myaudience.biz.model.HomeInfoModel;
import com.xiaoma.myaudience.biz.model.RankingListModel;
import com.xiaoma.myaudience.biz.model.ReviewListModel;
import com.xiaoma.myaudience.biz.task.DataAsyncTask;
import com.xiaoma.myaudience.biz.task.RankingMoreTask;
import com.xiaoma.myaudience.biz.task.ReviewListTask;
import com.xiaoma.myaudience.biz.task.ReviewMoreListTask;
import com.xiaoma.myaudience.biz.util.Constant;
import com.xiaoma.myaudience.biz.view.LoadingListView;
import com.xiaoma.myaudience.biz.view.RefreshableView;
import com.xiaoma.myaudience.biz.view.RefreshableView.PullToRefreshListener;
import com.xiaoma.myaudience.util.PrefHelper;
import com.xiaoma.myaudience.util.activity.BaseActivity;
import com.xiaoma.myaudience.util.model.ModelUtils;

/**
 * 评论页面.
 * 
 */
public class ReviewListActivity extends BaseActivity implements  OnItemClickListener, PullToRefreshListener{
    
    private static final String TAG = "ReviewListActivity";
    private static final int DIALOG_REFRESH = 0;
    private static final int MENU_REFRESH = Menu.FIRST;
    private String dateline;
    
    private ReviewListTask mRankingListTask;
    private LoadingListView mLoadingListView;
    private ReviewListAdapter mAdapter;
    private String mIndex;
    private String mEventId;
    private String mPicId;
    private String mType;
    private List<Map<String, Object>> mPicComment;
	private ReviewMoreListTask mActivitysMoreTask;
	private RefreshableView mRefreshableView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_view_page);
       
        mRefreshableView = (RefreshableView) findViewById(R.id.refresh_view);
        mLoadingListView = (LoadingListView) findViewById(R.id.hot_elv);
        mRefreshableView.setVisibility(View.VISIBLE);
        
        mRefreshableView.setOnRefreshListener(this, 1);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
        	mIndex = String.valueOf(bundle.getInt("tab_index"));
        	mEventId = bundle.getString("eventid");
        	mPicId = bundle.getString(HomeInfoModel.PARAM_PICID);
        	mType = bundle.getString(HomeInfoModel.PARAM_TYPE);
		}
        execute();
    }
    
    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	super.onResume();
    	execute();
    }
    
    @Override
    protected void onRestart() {
    	// TODO Auto-generated method stub
    	super.onRestart();
    	execute();
    }
    
    private void execute() {
    	cancel();
    	Map<String,String> cookie = new HashMap<String,String>();
		cookie.put(Constant.LOGIN_COOKIE1,PrefHelper.getString(ReviewListActivity.this, Constant.LOGIN_COOKIE1,""));
  		cookie.put(Constant.LOGIN_COOKIE2,PrefHelper.getString(ReviewListActivity.this, Constant.LOGIN_COOKIE2,""));
    	 if (TextUtils.isEmpty(mEventId)) {
    		 mRankingListTask = new ReviewListTask(this, DataAsyncTask.TASK_REVIEW, this, true);
    		 cookie.put("PID_CID", mPicId);
    		 cookie.put(RankingListModel.PARAM_TYPE, mType);
    		 mRankingListTask.execute(cookie);
		} else {
			mRankingListTask = new ReviewListTask(this, DataAsyncTask.TASK_REVIEW, this);
			cookie.put("PID_CID", mEventId);
			cookie.put(HomeInfoModel.PARAM_TYPE, mType);
			mRankingListTask.execute(cookie);
		}
	}
    
    private void cancel() {
    	if (mRankingListTask != null) {
    		mRankingListTask.cancel(true, true);
        }
    	mRankingListTask = null;
    }

    private void initData(List<Map<String, Object>> objMap, int type) {
    	try {
    		if (objMap == null && objMap.size() <= 0) {
    			mLoadingListView.showLoadingFailed();
    			return;
    		}
    		//取最后一条dateline
    		//getData(list);
    		dateline = (String) objMap.get(objMap.size() -1).get("dateline"); 
    		mAdapter = new ReviewListAdapter(this, objMap, type);
    		//LoadingListView listView = (LoadingListView) findViewById(R.id.hot_elv);
    		mLoadingListView.getListView().setAdapter(mAdapter);
    		mLoadingListView.getListView().setOnItemClickListener(this);
    		final int size = objMap.size();
    		mLoadingListView.getLoadingMoreButton().setOnClickListener(new OnClickListener() {
    			@Override
    			public void onClick(View v) {
    				// TODO Auto-generated method stub
    				if(!mLoadingListView.onClickDefaultMoreLayout()){
    					return;
    					//mLoadingListView.hideLoadingMoreLayout();
    				}
    				if (size == 0) {
    					mLoadingListView.hideLoadingMoreLayout();
    					return;
    				}
    				startLoadingMoreTask();
    			}
    		});
    		mAdapter.notifyDataSetChanged();
    		mLoadingListView.finishClickDefaultMoreLayout();
		} catch (Exception e) {
			
		}
    }

    @Override
    public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
    	Map<String, Object> item = (Map<String, Object>) adapter.getItemAtPosition(position);
    	if (item != null) {
//			Intent intent = new Intent(ReviewListActivity.this, ActivitysDetailActivity.class);
//			intent.putExtra(ActivityDetailInfoModel.PARAM_EVENTID, 
//					ModelUtils.getStringValue(item, ActivityDetailInfoModel.PARAM_EVENTID));
//			startActivity(intent);
		}
    }

    @Override
    public boolean onCreateOptionsNeteaseMenu(Menu menu) {
//    	((AudienceMainActivity)getParent()).onCreateOptionsNeteaseMenu(menu);
//        menu.add(0, MENU_REFRESH, 0, R.string.menu_refresh).setIcon(R.drawable.ic_menu_refresh);
        
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        if (!((AudienceMainActivity) getParent()).onMenuItemSelected(featureId, item)) {
            switch (item.getItemId()) {
                case MENU_REFRESH:
                    execute();
                    break;
            }
        }
        return true;
    }
    
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_REFRESH: {
                ProgressDialog dialog = new ProgressDialog(this);
                dialog.setMessage(getText(R.string.refresh_button));
                dialog.setOnCancelListener(new OnCancelListener() {                    
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (mRankingListTask != null) {
                        	mRankingListTask = null;
                        }                        
                    }
                });
                return dialog;
            }
        }
        return super.onCreateDialog(id);
    }
    
    public void refresh() {
        if (mRankingListTask != null) {
            cancel();
        }
        showDialog(DIALOG_REFRESH);        
    }
    
    //加载更多任务
    private void startLoadingMoreTask() {
    	mActivitysMoreTask = new ReviewMoreListTask(ReviewListActivity.this, DataAsyncTask.TASK_ACTIVITY_REVIEWMORELIST, ReviewListActivity.this);
    	Map<String,String> cookie = new HashMap<String,String>();
		cookie.put(Constant.LOGIN_COOKIE1,PrefHelper.getString(ReviewListActivity.this,Constant.LOGIN_COOKIE1,""));
		cookie.put(Constant.LOGIN_COOKIE2,PrefHelper.getString(ReviewListActivity.this,Constant.LOGIN_COOKIE2,""));
		cookie.put("type", mType);
		cookie.put("dateline", dateline);
    	mActivitysMoreTask.execute(cookie);
    }
    
    @Override
    public void onPostExecute(int what, Object o) {
        super.onPostExecute(what, o);
        switch (what) {
            case DataAsyncTask.TASK_REVIEW:
            	Map<String, Object> objMap = (Map<String, Object>) o;
            	if (objMap != null) {
            		ReviewActivity.mTitle = ModelUtils.getStringValue(objMap, ReviewListModel.PARAM_TITLE);
            		List<Map<String, Object>> list = ModelUtils.getListMapValue(objMap, ReviewListModel.PARAM_TEXT_COMENT);
            		mPicComment = ModelUtils.getListMapValue(objMap, ReviewListModel.PARAM_PIC_COMENT);
            		ReviewActivity.mEventId=ModelUtils.getStringValue(objMap, ReviewListModel.PARAM_EVENTID);
            		if ("2".equals(mIndex)) {
            			initData(list, 2);
					} else if ("1".equals(mIndex)) {
						initData(mPicComment, 1);
					}
				}
//                dismissDialog(DIALOG_REFRESH);
                break;
            case DataAsyncTask.TASK_ACTIVITY_REVIEWMORELIST:
            	Map<String, Object> mList = (Map<String, Object>) o;
            	if (o == null) {
            		mLoadingListView.finishClickDefaultMoreLayout();
            		mLoadingListView.hideLoadingMoreLayout();
					return;
				}
            	List<Map<String, Object>> list =  (List<Map<String, Object>>) o;
            	if (list.size() == 0) {
            		mLoadingListView.hideLoadingMoreLayout();
					return;
				}
            	List<Map<String, Object>> listdata = ModelUtils.getListMapValue(mList, ReviewListModel.PARAM_TEXT_COMENT);
            	//取最后一条dateline
            	//getData(list);
            	dateline = (String) listdata.get(listdata.size() -1).get("dateline"); 
            	mAdapter.notifyDataSetChanged();
            	mLoadingListView.finishClickDefaultMoreLayout();
            	break;
        }
        }

	@Override
	public void onRefresh() {
		try {
			execute();
			Thread.sleep(3000);
		} catch (Exception e) {
		}
		mRefreshableView.finishRefreshing();
	}
}
